﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Common
{
    /// <summary>
    /// Json 相关函数
    /// </summary>
    /// <remarks>
    /// <para>Fuyuanzhao</para>
    /// <para>2013.01.17</para>
    /// </remarks>
    public class JsonHelper
    {
        /// <summary>
        /// 根据Key获取Json字符串中value的值
        /// </summary>
        /// <param name="JsonRequest">Json字符串</param>
        /// <param name="RequestKey">键值</param>
        /// <returns>返回Value</returns>
        public static string GetValueFromJsonString(string JsonRequest, string RequestKey)
        {
            try
            {
                var mJObj = JObject.Parse(JsonRequest);

                if (mJObj[RequestKey] == null)
                    return string.Empty;

                return StringHelper.UrlDecode(mJObj[RequestKey].ToString());
            }
            catch
            {
            }

            try
            {
                var mJarry = JArray.Parse(JsonRequest);

                if (mJarry[RequestKey] == null)
                    return string.Empty;

                return StringHelper.UrlDecode(mJarry[RequestKey].ToString());
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 给已有的json添加键值
        /// </summary>
        /// <param name="Source"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public static string AddKeyValuePair(string Source, string Key, string Value)
        {
            int child = 0;
            try
            {
                var mJObj = JObject.Parse(Source);
                child = mJObj.Count;
            }
            catch
            { }

            if (child > 0)
                Source = Source.Insert(1, "\"" + Key + "\":\"" + Value + "\",");
            else
                Source = Source.Insert(1, "\"" + Key + "\":\"" + Value + "\"");

            return Source;
        }
    }
}
